package homework;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.net.URI;

public class WordCount {
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		// conf.set("HADOOP_USER", "hadoop");
		Job job = Job.getInstance(conf, "WordCount");// 设置环境参数
		job.setJarByClass(WordCount.class);// 设置整个程序的类名

		job.setMapperClass(WCMapper.class);
		job.setReducerClass(WCReduce.class);

		job.setOutputKeyClass(Text.class);// reduce输出类型
		job.setOutputValueClass(IntWritable.class);// 输出类型

		FileInputFormat.addInputPath(job, new Path("hdfs://192.168.3.101:9000/WordCount/input/test.txt"));
		// 如果文件系统已存在输出文件夹则删除
		FileSystem fs = FileSystem.get(new URI("hdfs://192.168.3.101:9000"), conf, "roger");
		if (fs.exists(new Path("/WordCount/output"))) {
			fs.delete(new Path("/WordCount/output"), true);
		}
		FileOutputFormat.setOutputPath(job, new Path("hdfs://192.168.3.101:9000/WordCount/output"));

		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

	public static class WCMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
		@Override
		protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
			// TODO Auto-generated method stub
			String[] words = value.toString().split("\\s+");
			for (String word : words) {
				context.write(new Text(word), new IntWritable(1));
			}

		}

	}

	public static class WCReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values, Context context)
				throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable value : values) {
				sum += value.get();
				// System.out.println(key.toString() + "\t" + value.toString());
			}
			context.write(key, new IntWritable(sum));

		}

	}

}
